package com.beici.waterghost.controller;


import com.beici.waterghost.model.resultes;
import com.beici.waterghost.model.user;
import com.beici.waterghost.service.impl.loginService;
import com.beici.waterghost.service.qq.login;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
public class loginController {

    @Autowired
    private loginService loginServer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private login qqLogin;

    @PostMapping("/login")
    public resultes login(String phone,String key,String code){
        // 验证下 该账号是否需要验证码
        boolean iscode = isCode(phone);
        if (iscode){
            if (code==null){
                return resultes.divResultes(null,"请输入验证码",2001);
            }
            // 验证code
            boolean b = verifityCode(phone, code);
            if (!b){
                return resultes.divResultes(null,"验证码错误",2001);
            }
        }

        resultes login = loginServer.login(phone, key);
        return login;
    }

    @PostMapping("/qqlogin")
    public resultes qqlogin(String openId,String userName,String userHeader){
        // 查出当前账号是否注册过
        long qqlogin = qqLogin.qqlogin(openId, userName, userHeader);
        resultes login = loginServer.login(String.valueOf(qqlogin), "123");
        return login;
    }

    /**
     * 验证当前账号是否需要输入code
     * @return
     */
    private boolean isCode(String phone){
        Integer s = 0;
        try {
             s = Integer.valueOf(redisTemplate.opsForValue().get(phone + "logincode"));
            if (s>=3){
                // 需要code
                return true;
            }
        }catch (NumberFormatException n){
            return  false;
        }
        return false;
    }

    /**
     * 验证 验证码是否正确
     * @return
     */
    private boolean verifityCode(String phone,String code){

        try{
            String s = redisTemplate.opsForValue().get(phone + "verifitycode");
            if (s.equals(code)){
                return true;
            }
        }catch (NullPointerException e){
            return false;
        }

        return false;
    }
}
